package com.ruoyi.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;

/**
 * Created by yangyincong on 15/8/16.
 * ID生成器 workId (1~4)
 */
public class IDGenerator {
	
	/**
     * 	数据中心ID
     */
    private  static long datacenterId = (long) new Random().nextInt(32);
    
    private  static long workerId = (long) new Random().nextInt(32);

    private static Snowflake snowflake;

    public static synchronized void init(){
    	int[] workData = getDataWorker();
     	workerId = (long) workData[0];
      	datacenterId = (long) workData[1];
        snowflake = IdUtil.getSnowflake(workerId, datacenterId);
    }
    
    public static int[] getDataWorker() {
    	String ipv4 = NetUtil.getLocalhostStr();
    	System.err.println("ipv4=============ipv4=============");
    	System.err.println("ipv4============="+ipv4+"=============");

    	String adder = ipv4.split("\\.")[3];
    	int sum  = 0;
    	for (int i = 1; i < 17; i++) {
			for (int j = 1; j < 17; j++) {
	    		String sumS = sum+"";
	    		if(sumS.equals(adder)) {
	    	    	System.err.println("workerId:"+i+"=======datacenterId:"+j+"========");
	    			return new int[] {i,j};
	    		}
				sum++; 
			}
		}
		return new int[] {new Random().nextInt(32),new Random().nextInt(32)};
    }

    public static Long generateId() {
        if (null == snowflake) {
            synchronized (IDGenerator.class) {
                if (null == snowflake) {
                	 init();
                }
            }
        }
        return snowflake.nextId();
    }
    

}
